<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2018 http://www.hisiphp.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

// 为方便系统升级，二次开发中用到的公共函数请写在此文件，禁止修改common.php文件
// ===== 系统升级时此文件永远不会被覆盖 =====
/**
 * 接口提交数据返回成功
 * @param $data 
 * @param string $msg
 * @param int $code
 */
function okMsg($data = [], $msg = 'success', $code = 200)
{
    header('Content-Type:application/json; charset=utf-8');
    $out = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
    exit(json_encode($out, JSON_UNESCAPED_UNICODE));
}


/**
 * 接口提交数据返回错误
 * @param string $msg
 * @param int $code (0:失败，302:失败,有返回数据)
 * @param $data
 */
function errMsg($msg = 'error', $code = 0, $data = [])
{
    header('Content-Type:application/json; charset=utf-8');
    $out = [
        'code' => $code,
        'msg' => $msg,
    ];
    if ($data) {
        $out['data'] = $data;
    }
    exit(json_encode($out, JSON_UNESCAPED_UNICODE));
}

function noLogin(){
    $out = [
        'code'=>-201,
        'msg'=>'noLogin'
    ];
    exit(json_encode($out, JSON_UNESCAPED_UNICODE));
}
/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function sp_random_string($len = 6) {
    $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    // file_put_contents('randNum.txt',$output."||",FILE_APPEND);
    return $output;
}

/**
 * 获取用户真实 IP
 */
function getIP()
{
    static $realip;
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}

/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
function getCity($ip = '')
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url = "http://api.map.baidu.com/location/ip?ak=6b6c1a67eaa7db1ca6d6da28e590e343&coor=bd09ll&ip=".$ip;
        $ip=json_decode(file_get_contents($url));
        if((string)$ip->status=='1'){
           return false;
        }
        $data = $ip->content->address_detail->city;
    }
    
    return $data;   
}

function curl_get_contents($url){  
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);//设置访问的url地址  
    //curl_setopt($ch, CURLOPT_POST, true);   
    //curl_setopt($ch, CURLOPT_POSTFIELDS, "IdCard={$content}");  
    //curl_setopt($ch,CURLOPT_HEADER,1);//是否显示头部信息  
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1');   //用户访问代理 User-Agent  
    curl_setopt($ch, CURLOPT_REFERER,"http://www.thinkpage.cn");//设置 referer  
    //curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);//跟踪301  
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);//设置超时  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回结果  
    curl_setopt($ch, CURLOPT_COOKIE, "");    
      
    $result = curl_exec($ch);     
    curl_close($ch);     
    return $result;     
}  

function getCurl($url){
    // echo $url;exit;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    curl_close ($ch);
    return $result;
}

function prDates($start,$end){ // 两个日期之间的所有日期  
    $dt_start = strtotime($start);  
    $dt_end = strtotime($end);  
    while ($dt_start<=$dt_end){  
        echo date('Y-m-d',$dt_start)."\n";  
        $dt_start = strtotime('+1 day',$dt_start);  
    }  
} 

function excel_export($excel_title = [],$data = [],$filename = '报表')
{
    $objPHPExcel = new \PHPExcel();

    array_unshift($data,$excel_title);
    //某一行
    foreach($data as $line_num => $line)
    {
        $row_num = 0;
        //所有列
        foreach($excel_title as $key => $row)
        {
            //内容位置
            $content_posi = chr($row_num+65).($line_num+1) ; // A1
            $content_val  = $line[$key];
            $objPHPExcel->getActiveSheet()->setCellValue($content_posi, $content_val);//可以指定位置
            $row_num++;
        }

    }
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$filename.'.xls"');
    header("Content-Disposition:attachment;filename=$filename.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}
/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url,$params=false,$ispost=0,$header=null){
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    //设置header头
    if(!empty($header)){
        curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return curl_error($ch);
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}

function sendNotice($mobile,$order_id,$keshi,$bed,$phone){
    header('content-type:text/html;charset=utf-8');
    // $mobile = '13480250742';
    
    // var_dump(EXTEND_PATH);exit;
    import('sms.SmsDemo', EXTEND_PATH);
    // import('wxpay.lib.WxPayApi',EXTEND_PATH);
    $sys = new \SmsDemo();
    $rs = $sys->sendNotice($mobile,$order_id,$keshi,$bed,$phone);
    // var_dump($rs);exit;
    
}

function getHmac($data){
    $rs = md5($data.config('huiju_appsecret'));
    return $rs;
}

function create_log($log_name,$data){
    $request = \think\Request::instance();
    $controller = $request->controller();
    $action = $request->action();
    $mulu = ROOT_PATH.'public\\project_log\\'.$controller.'\\'.$action.'\\';
    $pathArr = explode("\\", $mulu);
    $pathed="";
    foreach ($pathArr as $key=>$row) {
        $pathed=$pathed.$row."\\";
        if ($key==0) {
            continue;
        }
        if (is_dir($pathed)) {
            continue;
        }
        else{
            mkdir($pathed);
        }
    }
    file_put_contents($mulu.$log_name,var_export($data, true).date('Y-m-d H:i:s',time()) . PHP_EOL, FILE_APPEND);
}

function curlPost($url, $data,$type='xml'){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    if($type=='json'){
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data))
        );
    }else{
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    }
    
    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    return $tmpInfo;
}